package com.example.administrator.xmut.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.administrator.xmut.MainActivity;
import com.example.administrator.xmut.R;
import com.example.administrator.xmut.http.CourseBean;
import com.example.administrator.xmut.http.utils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import org.apache.http.Header;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LoginActivity extends AppCompatActivity {
    public static String name="1407012215";
    public static String password="TamoQin0701";
    public static String gotourl="http://my.xmut.edu.cn/loginSuccess.portal";
    public static String gotoOnfail= "http://my.xmut.edu.cn/loginFailure.portal";
    public static String posturl="http://my.xmut.edu.cn/userPasswordValidate.portal";
    public static String geturl="http://my.xmut.edu.cn/index.portal";
    private RelativeLayout mProgress;
    private TextView mText;



    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        mProgress = (RelativeLayout) findViewById(R.id.progress_layout);
        mText = (TextView) findViewById(R.id.textView2);

        onProgressChanged(0);
            // 发送请求到服务器
            AsyncHttpClient client = new AsyncHttpClient();
            // 创建请求参数
            RequestParams params = new RequestParams();
            params.put("Login.Token1", name);
            params.put("Login.Token2", password);
            params.put("goto", gotourl);
            params.put("gotoOnfail", gotoOnfail);
            // 执行post方法,并保存cookies
            saveCookie(client);

            client.post(posturl, params, new AsyncHttpResponseHandler() {
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    utils.setCookies(getCookie());
                    onProgressChanged(25);
                    // 创建异步请求端对象
                    onProgressChanged(40);


                    AsyncHttpClient client1 = new AsyncHttpClient();
                    if (utils.getCookies() != null) {//每次请求都要带上cookie
                        BasicCookieStore xxzxcookies = new BasicCookieStore();
                        xxzxcookies.addCookies(utils.getCookies().toArray(
                                new Cookie[utils.getCookies().size()]));
                        client1.setCookieStore(xxzxcookies);
                        // 发送get请求对象
                        client1.get(geturl, new AsyncHttpResponseHandler() {
                            Element name = null;
                            String jwxturl = null;
                            @Override
                            // statusCode:状态返回码，headers:头部请求信息，responseBody返回结果


                            public void onSuccess(int statusCode, Header[] headers, final byte[] responseBody) {
                                onProgressChanged(90);
                                try {
                                    String resultContent = new String(responseBody, "utf-8");
                                    Document doc = Jsoup.parse(resultContent);
                                    jwxturl=doc.select("[href~=(default2)]").toString();
                                    Pattern pattern = Pattern.compile("href=['\"]([^'\"]*)['\"]");
                                    Matcher matcher = pattern.matcher(jwxturl);
                                    String aa = null;
                                    if(matcher.find())
                                        aa=matcher.group(1);
                                    jwxturl=aa.replace("amp;", "");
                                    SharedPreferences mySharedPreferences= getSharedPreferences("test",
                                            MainActivity.MODE_PRIVATE);
                                    SharedPreferences.Editor editor = mySharedPreferences.edit();
                                    name = doc.getElementById("welcomeMsg");
                                    editor.putString("jwxturl", jwxturl);
                                    editor.putString("username", name.html());
                                    editor.commit();
                                    final String username = name.html();
                                    final Handler mHandler = new Handler() {
                                        public void handleMessage(android.os.Message msg) {
                                            mText.setText((String) msg.obj);
                                        }
                                    };

                                    class DataThread extends Thread {


                                        public void run() {
                                            final String data = username;
                                                mHandler.sendMessage(mHandler.obtainMessage(0, data));
                                                try {
                                                    Thread.currentThread().sleep(2000);
                                                } catch (InterruptedException e1) {
                                                    e1.printStackTrace();
                                                }
                                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                                // new Thread(LoginJWXT).start();
                                                startActivity(intent);
                                                clearCookie();
                                                finish();
                                        }
                                    }
                                    new DataThread().start();
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }

                        });
                    }
                }
            });

    }



    //progresschange
    public void onProgressChanged (int newProgress) {

        if (newProgress == 100) {
            mProgress.setVisibility(View.GONE);
        }else {
            mText.setText("正在登陆...");
        }

    }


    //保存cookies的方法
    protected  void saveCookie(AsyncHttpClient client) {
        PersistentCookieStore cookieStore = new PersistentCookieStore(this);
        client.setCookieStore(cookieStore);
    }

    protected List<Cookie> getCookie(){
        PersistentCookieStore cookieStore = new PersistentCookieStore(this);
        List<Cookie> cookies = cookieStore.getCookies();
        return cookies;
    }

    public void clearCookie(){
        PersistentCookieStore cookieStore = new PersistentCookieStore(this);
        cookieStore.clear();
    }


}
